<?php

namespace app\controller;

use app\BaseController;
use app\model\ActivityGoods;
use app\model\ApplySamples;
use app\model\DarenSwBind;
use app\model\DyUser;
use app\model\DyUserAddress;
use app\model\ExpressCompany;
use app\model\UserInfo;
use app\model\Wiseman;
use app\traits\TemplateMsgTrait;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use app\traits\CommonTrait;
use app\model\User;

class Sample extends BaseController
{
    use CommonTrait;
    use TemplateMsgTrait;

    //显示商务用户列表
    public function userList()
    {
        $uid = 20;
        $userList = User::with(['role' => function ($query) {
            $query->where(['rid' => 4])->field('uid,rid');
        }])->where(['id' => $uid])->find();
        return $this->apiJson(1, '', $userList);
    }

    //申请领样
    public function applySample()
    {
        $uid = getUid();
        $goodsId = Request::post('goods_id');
        $dyUserId = Request::post('dy_user_id', 0);
        $addressId = Request::post('address_id', 0);
        $remark = Request::post('remark', '');
        if (!$goodsId) {
            return $this->apiJson(-1, '商品不存在或已下架');
        }
        $goodsIdArr = explode(',', $goodsId);
        $count = ActivityGoods::whereIn('id', $goodsId)->where(['status' => 1])->count();
        if ($count != count($goodsIdArr)) {
            return $this->apiJson(-1, '参数错误');
        }
        if (!$dyUserId) {
            return $this->apiJson(-1, '带货抖音号不存在');
        }
        $dyUser = DyUser::where(['user_id' => $uid, 'id' => $dyUserId])->field('id,dy_uid')->findOrEmpty();
        if ($dyUser->isEmpty()) {
            return $this->apiJson(-1, '带货抖音号不存在');
        }
        if (!$addressId) {
            return $this->apiJson(-1, '收货地址不存在');
        }
        $address = DyUserAddress::where(['user_id' => $uid, 'id' => $addressId])->field('id,name,phone,province,city,district,detail_address')->findOrEmpty();
        if ($address->isEmpty()) {
            return $this->apiJson(-1, '收货地址不存在');
        }
        if (mb_strlen($remark) > 100) {
            return $this->apiJson(-1, '备注不能超过100个字');
        }
        //检测是否有绑定商务,没绑定的就用系统默认的商务
        $swUserId = DarenSwBind::where(['dr_user_id' => $uid])->value('sw_user_id');
        if (!$swUserId) {
            $swUserId = 1;
        }
        $sampleNo = $this->generateSampleNo();
        $data = [];
        foreach ($goodsIdArr as $k => $v) {
            $data[$k] = [
                'user_id' => $uid,
                'sample_no' => $sampleNo,
                // todo 暂定的用户id
                'sw_user_id' => $swUserId,
                'activity_goods_id' => $v,
                'dy_uid' => $dyUser['dy_uid'],
                'contact_name' => $address['name'],
                'contact_phone' => $address['phone'],
                'address' => $address['province']['name'] . $address['city']['name'] . $address['district']['name'] . $address['detail_address'],
                'remark' => $remark,
                'create_time' => date('Y-m-d H:i:s', time()),
                'update_time' => date('Y-m-d H:i:s', time())
            ];
        }
        Db::name('apply_samples')->insertAll($data);
        return $this->apiJson(1, 'success');
    }

    //申请领样列表
    public function applySampleList()
    {
        $uid = getUid();
        // -1全部 0待发样 1已发样 2已取消
        $status = Request::get('status', -1);
        $currentPage = Request::get('current_page') ? Request::get('current_page') : 1;
        $perPage = $this->getPerPage();
        $title = Request::get('title', '');
        $where = $goodsWhere = [];
        if ($status != -1) {
            $where[] = ['apply_samples.status', '=', $status];
        }
        if ($title) {
            $goodsWhere[] = ['product_name|sample_no', 'like', "%" . $title . "%"];
        }
        $applyList = ApplySamples::hasWhere('goods', $goodsWhere, 'id,dy_uid,activity_goods_id,status')
            ->with(['dy' => function ($query) {
                $query->field('id,nickname as dy_name,author_id');
            }])
            ->where($where)
            ->where(['user_id' => $uid])
            ->field('product_name,product_img,promotion_price,commission,commission_rate,common_commission_rate,shop_ids,shop_name,express_name,express_no')
            ->order('apply_samples.update_time', 'desc')
            ->paginate(['page' => $currentPage, 'list_rows' => $perPage]);
        return $this->apiJson(1, 'success', $applyList);
    }

    //取消申请领样
    public function cancelSample()
    {
        $uid = getUid();
        $id = Request::post('id', 0);
        if (!$id) {
            return $this->apiJson(-1, '缺少id参数');
        }
        $apply = ApplySamples::where(['id' => $id, 'user_id' => $uid, 'status' => 0])->findOrEmpty();
        if ($apply->isEmpty()) {
            return $this->apiJson(-1, '参数错误');
        }
        ApplySamples::where(['id' => $id, 'user_id' => $uid])->update(['status' => 2]);
        return $this->apiJson(1, 'success');
    }

    //达人样品详情
    public function sampleDetail()
    {
        $uid = getUid();
        $id = Request::get('id', 0);
        if (!$id) {
            return $this->apiJson(-1, '缺少id参数');
        }
        $apply = ApplySamples::where(['id' => $id, 'user_id' => $uid])->findOrEmpty();
        if ($apply->isEmpty()) {
            return $this->apiJson(-1, '无权限操作');
        }
        $sampleDetail = ApplySamples::with(['goods' => function ($query) {
            $query->field('id,product_name,product_img,promotion_price,commission,commission_rate,common_commission_rate,shop_ids,shop_name');
        }, 'dy' => function ($query) {
            $query->field('id,author_id,phone,nickname as dy_name,city,avatar,fans_num as fans,link_num as likes,
            works_num as works,introduction as dy_intro,goods_main_cate as dh_cate_tag,user_id');
        }])
            ->where(['user_id' => $uid, 'id' => $id])
            ->field('id,dy_uid,sample_no,contact_name,contact_phone,address,address,activity_goods_id,status,remark,express_name,express_no,create_time')
            ->find();
        return $this->apiJson(1, 'success', $sampleDetail);
    }

    /*
     * 商务
     * */
    //发样管理列表
    public function sendSampleList()
    {
        $uid = getUid();
        // -1全部 0待发样 1已发样
        $status = Request::get('status', -1);
        $currentPage = Request::get('current_page') ? Request::get('current_page') : 1;
        $perPage = $this->getPerPage();
        $title = Request::get('title', '');
        $where = $goodsWhere = [];
        if (in_array($status, [0, 1])) {
            $where[] = ['apply_samples.status', '=', $status];
        } else {
            $where[] = ['apply_samples.status', '<>', 2];
        }
        if ($title) {
            $goodsWhere[] = ['product_name|sample_no', 'like', "%" . $title . "%"];
        }
        $applyList = ApplySamples::hasWhere('goods', $goodsWhere, 'id,dy_uid,activity_goods_id,status')
            ->with(['dy' => function ($query) {
                $query->field('id,nickname as dy_name,author_id');
            }])
            ->where($where)
            ->where('sw_user_id', $uid)
            ->field('dy_uid,user_id,product_name,product_img,promotion_price,commission,commission_rate,common_commission_rate,shop_ids,shop_name,express_name,express_no,type')
            ->order('apply_samples.update_time', 'desc')
            ->paginate(['page' => $currentPage, 'list_rows' => $perPage]);
        return $this->apiJson(1, 'success', $applyList);
    }

    public function expressCompany()
    {
        $express = ExpressCompany::select();
        return $this->apiJson(1, 'success', $express);
    }

    //填写快递单号
    public function expressNoWrite()
    {
        $uid = getUid();
        $sampleId = Request::post('sample_id');
        $expressNo = Request::post('express_no');
        $expressCompanyId = Request::post('express_company_id');
        if (!$sampleId) {
            return $this->apiJson(-1, '缺少sample_id参数');
        }
        //待发样
        $sample = ApplySamples::where(['id' => $sampleId, 'status' => 0])
            ->field('id,sample_no,user_id,activity_goods_id,dy_uid,contact_name,contact_phone,address,status')
            ->findOrEmpty();
        if ($sample->isEmpty()) {
            return $this->apiJson(-1, '参数错误');
        }
        $expressPreg = '/[A-Za-z0-9]{8,20}$/';
        $isExpress = preg_match($expressPreg, $expressNo, $express);
        if (!$isExpress) {
            return $this->apiJson(-1, '快递单号不合法');
        }
        //是否是商务下合法的申请带货的达人
        $drExist = DarenSwBind::where(['sw_user_id' => $uid, 'dr_user_id' => $sample['user_id']])->findOrEmpty();
        if ($drExist->isEmpty()) {
            return $this->apiJson(-1, '参数错误');
        }
        //检测快递公司是否存在
        $expressCompanyExist = ExpressCompany::where(['id' => $expressCompanyId])->findOrEmpty();
        if ($expressCompanyExist->isEmpty()) {
            return $this->apiJson(-1, '物流公司不存在');
        }
        ApplySamples::where(['id' => $sampleId, 'status' => 0])->update(['express_no' => $expressNo, 'express_name' => $expressCompanyExist['name'], 'status' => 1]);
        Wiseman::where(['author_id' => $sample['dy_uid']])->update(['is_worked' => 1, 'user_id' => $uid]);
        $openId = UserInfo::where(['user_id'=>$sample['user_id']])->value('openid');
        if($openId){
            $productName = ActivityGoods::where(['id'=>$sample['activity_goods_id']])->value('product_name');
            $templateId = config('app.template.sample_notice');
            $pagePath = 'pakeageDaren/pages/select/index?title='.$sample['sample_no'];
            $data = [
                "first" => [
                    "value" => "嗖嗖嗖，你申请的领样商品已经发货啦"
                ],
                "keyword1" => [
                    "value" => $productName
                ],
                "keyword2" => [
                    "value" => $expressCompanyExist['name']
                ],
                "keyword3" => [
                    "value" => $expressNo
                ],
                "keyword4" => [
                    "value" =>$sample['contact_name'].' '.$sample['contact_phone'].' '.$sample['address']
                ],
                "remark" => [
                    "value" => "点击查看领样详情"
                ],
            ];
            $result = $this->uniformMessageSend($openId, $templateId, $data,$pagePath);
            if ($result['code'] != 1) {
                Log::info($result);
            }
        }
        return $this->apiJson(1, 'success');
    }


    //商务 领样详情
    public function swSampleDetail()
    {
        $uid = getUid();
        $id = Request::get('sample_id', 0);
        if (!$id) {
            return $this->apiJson(-1, '缺少sample_id参数');
        }
        $sampleDetail = ApplySamples::with(['goods'=>function($query){
            $query->field('id,product_name,product_img,promotion_price,commission,commission_rate,common_commission_rate,shop_ids,shop_name');
        },'dy'=>function($query){
            $query->field('id,dy_id,author_id,phone,nickname as dy_name,city,avatar,fans_num as fans,link_num as likes,
            works_num as works,introduction as dy_intro,goods_main_cate as dh_cate_tag,user_id');
        }])->where(['id' => $id,'sw_user_id' => $uid])
            ->field('id,user_id,sample_no,dy_uid,type,contact_name,contact_phone,address,address,dy_uid,activity_goods_id,status,remark,express_name,express_no,create_time')
            ->findOrEmpty();
        if ($sampleDetail->isEmpty()) {
            return $this->apiJson(-1, '领样记录不存在');
        }
        if (isset($sampleDetail['dy']['user_id'])&&$sampleDetail['dy']['user_id'] != 0) {
            $user = User::where(['id' => $sampleDetail['dy']['user_id']])->field('name,wx_nickname')->find();
            $userName = $user['name'];
            $wxNickname = $user['wx_nickname'];
        } else {
            $userName = '';
            $wxNickname = '';
        }
        $sampleDetail['user_name'] = $userName;
        $sampleDetail['wx_nickname'] = $wxNickname;
        return $this->apiJson(1, 'success', $sampleDetail);
    }
}
